<?php

namespace App\Http\Middleware;
use App\Http\Model\User;
use Closure;

use EasyWeChat\Payment\Order;
use EasyWeChat\Foundation\Application;
use Intervention\Image\Facades\Image;
use DB;
use Config;
use EasyWeChat\Message\Text;
class Auths
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next){
        if(!$request->input('code') && strpos($_SERVER['REQUEST_URI'], "from=singlemessage") && empty(session('uid'))){
            $domain_name = Config::get('app.domain_name');
            $app_id = Config::get('wechat.app_id');
            $url = "http://www.tlbc99.com".explode("?", $_SERVER['REQUEST_URI'])[0];
            // dd($url);
            echo "<script>location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$app_id."&redirect_uri=".$url."&response_type=code&scope=snsapi_userinfo&state=0#wechat_redirect/'</script>";
            die;
        }
        if($request->input('code') && empty(session('uid'))){
            $user = New User;
            // 获取 OAuth 授权结果用户信息
            $app = app('wechat');
            $oauth = $app->oauth;
            $userInfo = $oauth->user();
            $userData = $user->where('open_id',$userInfo->id)->first();
            if($userData){
                session(['uid'=>$userData->id]);
                session(['identity'=>$userData->identity]);
            }else{
                $userArr=array();
                $userArr['open_id'] = $userInfo->token->openid;
                $userArr['sex'] = $userInfo->original['sex'];
                $userArr['username'] = $userInfo->nickname;
                $userArr['face'] = $userInfo->avatar;
                $userArr['province'] = $userInfo->original['province'];
                $userArr['city'] = $userInfo->original['city'];
                $userArr['country'] = $userInfo->original['country'];
                $id = DB::table('user')->insertGetId($userArr);
                session(['uid'=>$id]);
                session(['identity'=>0]);
            }
            return $next($request);
        }else{
            return $next($request);
        }
    }
}
